package com.codeduck.properties;

import com.codeduck.properties.byAnnotation.ProducerProperties;
import com.codeduck.properties.byAnnotation.RedisProperties;
import com.codeduck.properties.byEnvironment.DefaultProperties;
import com.codeduck.properties.byFile.KafkaConsumerProperties;
import com.codeduck.properties.byFile.KafkaProducerProperties;
import com.codeduck.properties.byJava.ZookeeperProperties;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.core.env.Environment;
import org.springframework.core.io.ClassPathResource;

import java.util.Properties;

/**
 * @author: <a href="mailto:codeduck@163.com">Codeduck</a>
 * @since: 2021-12-22
 */
@SpringBootApplication
public class PropertiesApplication {

    public static void main(String[] args) {
        SpringApplication.run(PropertiesApplication.class, args);

        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(RedisProperties.class);
        // 方式一：利用@PropertySource与@Value注解注入指定配置文件内容
        RedisProperties redisProperties = context.getBean(RedisProperties.class);
        System.out.println(redisProperties.getServer());

        // 方式二：通过 Environment Bean获取已经载入Spring容器中的配置变量（Spring默认读取 classpath:application.yml 或 classpath:application.properties 配置文件）
        context = new AnnotationConfigApplicationContext(DefaultProperties.class);
        Environment environment = context.getBean(Environment.class);
        System.out.println(environment.getProperty("user.fullName"));

        // 方式三：通过上下文容器获取已注入的JavaBean，设置配置文件路径获取properties
        context = new AnnotationConfigApplicationContext(KafkaConsumerProperties.class);
        KafkaConsumerProperties consumerProperties = context.getBean(KafkaConsumerProperties.class);
        Properties consumerProps = consumerProperties.getConsumerProperties("classpath:META-INF/kafka-consumer.properties");
        System.out.println(consumerProps);

        context = new AnnotationConfigApplicationContext(KafkaProducerProperties.class);
        KafkaProducerProperties producerProperties = context.getBean(KafkaProducerProperties.class);
        ClassPathResource classPathResource = new ClassPathResource("META-INF/kafka-producer.properties");
        Properties producerProps = producerProperties.getProducerProperties(classPathResource);
        System.out.println(producerProps);

        // 方式四：通过Java获取配置文件
        Properties zookeeperProps = ZookeeperProperties.getProperties();
        System.out.println(zookeeperProps);
    }
}
